package com.southwind.springboottest.study.Java中通讯.tcp协议案例;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) {
        int port = 12345; // 服务器监听的端口号
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("TCP Server is listening on port " + port);

            // 等待客户端连接
            Socket socket = serverSocket.accept();

            // 获取输入流和输出流
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

                // 读取客户端发送的消息
                String message = in.readLine();
                System.out.println("Received: " + message);

                // 发送回客户端的响应
                out.println("Echo: " + message);
            }
        } catch (IOException e) {
            e.printStackTrace(); // 处理 I/O 异常
        }
    }
}

